/**
 * ProjectDbDao.java
 *
 * Copyright (c) 2010 Prj.Manager All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of Prj.Manager .
 **/

package ro.prjmanager.dao;

import org.hibernate.Query;
import ro.prjmanager.core.dao.GenericDAO;
import ro.prjmanager.core.list.ListSqlParser;
import ro.prjmanager.core.list.SQL;
import ro.prjmanager.core.usr.UserSession;
import ro.prjmanager.model.DataBases;
import ro.prjmanager.model.ProjectDb;
import ro.prjmanager.model.Projects;
import ro.prjmanager.model.Schema;

import java.util.List;

/**
 * This interface provides custom method declaration for ProjectDb
 * entity and has a default implementation in the same package :
 * ProjectDbDAOImpl
 * @author Viorel Tacliciu
 * @version 4
 */

@SuppressWarnings("unchecked")
public class ProjectDbDao extends GenericDAO<ProjectDb,  java.lang.Integer> {

    @Override
    public List<ProjectDb> listPagFilter(int startPage, int resPerPage, String sqlFilter) {
        StringBuilder sql=new StringBuilder("select c from ").append(getPersistentClass().getName()).append(" as c ");

          SQL sqlFilterParsed = ListSqlParser.parseSqlListParameter(sqlFilter);
        sql.append(" ").append(sqlFilterParsed.getBeforeWhereParent());


        sql.append(" where c.fkProject.id=")
                .append(((Projects)getUserSession().getProject()).getId());
       sql.append(" ").append(sqlFilterParsed.getAfterWhereParent());

        Query sqlQuery=getSession().createQuery(sql.toString());
        sqlQuery.setMaxResults(resPerPage);
        sqlQuery.setFirstResult(startPage);
        return sqlQuery.list();
    }

    public ProjectDb getCurrentProjectDb(){
        UserSession userSession=getUserSession();
        Integer idProj=((Projects)getUserSession().getProject()).getId();
        Integer idDb=((DataBases)userSession.getDataBases()).getId();
        Integer idSchema=((Schema)userSession.getSchema()).getId();
        Query query=getSession().createQuery("select c from "+getPersistentClass().getName()
                +" as c join c.fkDbSchema as d where c.fkProject.id="+idProj+
                " and d.fkDatabase.id="+idSchema+" and d.fkSchema.id="+idSchema);
        List<ProjectDb> projectDbs= query.list() ;
        assert projectDbs!=null;
        return projectDbs.get(0);
    }

}
